/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.commodity.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.wealth.commodity.entity.Comment;
import com.wealth.commodity.entity.Goods;
import com.wealth.commodity.repository.CommentDao;
import com.wealth.commodity.service.ICommentService;
import com.wealth.order.entity.Order;
import com.wealth.order.entity.OrderItem;
import com.wealth.order.repository.OrderDao;
import com.wealth.order.repository.OrderItemDao;

import iaas.enums.StatusEnum;
import iaas.enums.YesOrNoEnum;
import iaas.persistence.DynamicSpecifications;
import iaas.persistence.SearchFilter;
import iaas.persistence.SearchFilter.Operator;
import iaas.service.impl.BaseServiceImpl;
import iaas.utils.Reflections;
import iaas.utils.ResultObject;
import iaas.web.JqGridRequest;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */
 
@Component
public class CommentServiceImpl extends BaseServiceImpl<Comment> implements ICommentService{

	@Autowired
	private CommentDao commentDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private OrderItemDao itemDao;
	public Page<Comment> get(Long corpid, Long merchantId, JqGridRequest request,
			Class<Comment> comment) {
		//创建分页请求.
		int pageNumber = request.getPage();
		int pageSize = request.getRows();
		String sortType = StringUtils.isEmpty(request.getSidx())?"id":request.getSidx();
		String sortDirection = StringUtils.isEmpty(request.getSord())?"desc":request.getSord();
		Direction direction = sortDirection.equals("desc")?Direction.DESC:Direction.ASC;
		Sort sort = new Sort(direction, sortType);
		PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, sort);

		//创建动态查询条件组合.
		Collection<SearchFilter> filters = SearchFilter.parse(request);
		//过滤:企业
		if(Reflections.existsField("corp", comment)){
			if(corpid!=1L){
				filters.add(new SearchFilter("corp.id", Operator.EQ, corpid));
			}
		}
		//过滤:商户
		filters.add(new SearchFilter("goods.merchant.id", Operator.EQ, merchantId));
		//过滤:状态
		if(Reflections.existsField("status", comment)){
			filters.add(new SearchFilter("status", Operator.NE, StatusEnum.DELETE.getValue()));
		}
		Specification<Comment> spec = DynamicSpecifications.bySearchFilter(filters, comment);
		
		return commentDao.findAll(spec, pageRequest);
	}

	
	/** 发表评论 */
	public ResultObject saveComment(Comment comment){
		
		List<Comment> temp = commentDao.findByMemberIdAndOrderIdAndGoodsId(comment.getMember().getId(), comment.getOrder().getId() ,comment.getGoods().getId());
		if(temp.size()>=1){
			return new ResultObject("500", "重复提交评价", "");
		}
		
		//保存评论
		comment.setCreateTime(new Date());
		comment.setStatus(StatusEnum.NORMAL.getValue());
		commentDao.save(comment);
		//修改订单
		Order order = orderDao.findOne(comment.getOrder().getId()) ;
		order.setEvaluatestatus(YesOrNoEnum.YES.getValue());
		orderDao.save(order);
		
		return new ResultObject("000", "评价成功", "");
		
	}
	/** 发表评论 */
	public ResultObject saveCommentPc(Comment comment,Long orderItemId){
		List<Comment> temp = commentDao.findByMemberIdAndOrderIdAndGoodsId(comment.getMember().getId(), comment.getOrder().getId() ,comment.getGoods().getId());
		if(temp.size()>=1){
			return new ResultObject("500", "重复提交评价", "");
		}
		//保存评论
		comment.setCreateTime(new Date());
		comment.setStatus(StatusEnum.NORMAL.getValue());
		commentDao.save(comment);
		/**修改订单item状态*/
		OrderItem item =itemDao.findOne(orderItemId);
		item.setCommentstatus(YesOrNoEnum.YES.getValue());
		itemDao.save(item);
		//修改订单
		/*Order order = orderDao.findOne(comment.getOrder().getId()) ;
		order.setEvaluatestatus(YesOrNoEnum.YES.getValue());
		orderDao.save(order);*/
		
		return new ResultObject("000", "评价成功", "");
		
	}
	
	
	/** 加载商户评价 */
	public List<Comment> ajaxCommentByMerchantId(Long merchantid, Integer index,Integer offset) throws Exception{
		
		/** ---- 分页查询 ---*/
		//创建分页请求.
		Sort sort = new Sort(Direction.DESC,"id");
		PageRequest pageRequest = new PageRequest(0, offset, sort);
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		//过滤:会员
		filters.add(new SearchFilter("goods.merchant.id", Operator.EQ, merchantid));
		//过滤:状态
		filters.add(new SearchFilter("status", Operator.EQ, StatusEnum.NORMAL.getValue()));
		//过滤：id<index
		if(index!=-1){
			filters.add(new SearchFilter("id", Operator.LT, index));
		}
		Specification<Comment> spec = DynamicSpecifications.bySearchFilter(filters, Comment.class);
		Page<Comment> page  = 	commentDao.findAll(spec, pageRequest);
		return page.getContent();
	}
	
	/** 商户最近的评论  前offset条 */
	public List<Comment>  getLatestCommentByMerchantId(Long merchantid,Integer offset) throws Exception{
		return commentDao.getLatestCommentByMerchantId(merchantid, offset);
	}
	
	/** 商户评价平均分数  */
	@Override
	public Integer getAvgScoreByMerchantId(Long merchantid) throws Exception {
		Integer avg = commentDao.getAvgScoreByMerchantId(merchantid);
		if(avg==null){
			avg = 10;
		}
		return avg;
	}
	
	/** 商户评价总数 */
	@Override
	public Integer getCommentNumByMerchantId(Long merchantid) throws Exception {
		Integer sum = commentDao.getCommentNumByMerchantId(merchantid);
		if(sum==null){
			sum = 10;
		}
		return sum;
	}
	
	
	
	
	
	/** 加载商品评价 */
	public List<Comment> ajaxComment(Long goodsid, Integer index,Integer offset) throws Exception{
		
		/** ---- 分页查询 ---*/
		//创建分页请求.
		Sort sort = new Sort(Direction.DESC,"id");
		PageRequest pageRequest = new PageRequest(0, offset, sort);
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		//过滤:会员
		filters.add(new SearchFilter("goods.id", Operator.EQ, goodsid));
		//过滤:状态
		filters.add(new SearchFilter("status", Operator.EQ, StatusEnum.NORMAL.getValue()));
		//过滤：id<index
		if(index!=-1){
			filters.add(new SearchFilter("id", Operator.LT, index));
		}
		Specification<Comment> spec = DynamicSpecifications.bySearchFilter(filters, Comment.class);
		Page<Comment> page  = 	commentDao.findAll(spec, pageRequest);
		return page.getContent();
	}
	
	/** 商品最近的评论  前offset条 */
	public List<Comment>  getLatestComment(Long goodsid,Integer offset) throws Exception{
		return commentDao.getLatestComment(goodsid, offset);
	}
	
	/**商品评价平均分数  */
	@Override
	public Integer getAvgScore(Long goodsid) throws Exception {
		Integer avg = commentDao.getAvgScore(goodsid);
		if(avg==null){
			avg = 0;
		}
		return avg;
	}
	
	/** 商品评价总数 */
	@Override
	public Integer getCommentNum(Long goodsid) throws Exception {
		Integer sum = commentDao.getCommentNum(goodsid);
		if(sum==null){
			sum = 0;
		}
		return sum;
	}


	@Override
	public Map<String, Object> getComment(int pageNumber, int pageSize,
			String sortType, String sortDirection,Long goodsId) {
			//创建分页请求.
			Direction direction = sortDirection.equals("desc")?Direction.DESC:Direction.ASC;
			Sort sort = new Sort(direction, sortType);
			PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, sort);
			
			//创建动态查询条件组合.
			Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
			filters.add(new SearchFilter("status", Operator.EQ, StatusEnum.NORMAL.getValue()));
			filters.add(new SearchFilter("goods.id", Operator.EQ, goodsId));
			Specification<Comment> spec = DynamicSpecifications.bySearchFilter(filters, Comment.class);
			Page page = commentDao.findAll(spec, pageRequest);
			Long count = page.getTotalElements();
			List<Comment> selPro = page.getContent();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("count", count);//分页所需的分类总数
			map.put("list", selPro);//分页集合
			return map;
	}
	
	
	
	
	
}


